from contextlib import contextmanager

@contextmanager
def my_open(filename,filemode):
    try:
        file=open(filename,filemode)
        # yield 之前的代码可以认为是上文方法，负责返回操作对象的资源
        yield file
    except Exception as e:
        print(e)
    finally:
        file.close()

with my_open("1.txt","r") as file:
    filedata=file.read()
    print(filedata)